package common

import (
	"fmt"
	"github.com/go-redis/redis"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
	"khao.fun/shizhan/migration"
)

var DB *gorm.DB
// RedisClient Redis缓存客户端单例
var RedisClient *redis.Client

func InitDB() *gorm.DB {

	driverName := viper.GetString("datasource.driverName")
	host := viper.GetString("datasource.host")
	port := viper.GetString("datasource.port")
	database := viper.GetString("datasource.database")
	username := viper.GetString("datasource.username")
	password := viper.GetString("datasource.password")
	charset := viper.GetString("datasource.charset")
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		username, password, host, port, database, charset)
	db, err := gorm.Open(driverName, args)
	if err != nil {
		panic(err)
	}
	migration.SetAutoMigrate(db)
	DB = db
	return DB
}
func GetDB() *gorm.DB {
	return DB
}

//func GetRedis() *redis.Client {
//	return RedisClient
//}

func InitRedis() *redis.Client {
	addr := viper.GetString("datasource.redis.addr")
	db := viper.GetInt("datasource.redis.db")
	password := viper.GetString("datasource.redis.password")
	client := redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: password,
		DB:       db,
	})

	_, err := client.Ping().Result()
	if err != nil {
		panic(err)
	}

	RedisClient = client
	return RedisClient
}